package com.mxpio.erp.inventory.controller;


import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.inventory.entity.FeedPlanNotice;
import com.mxpio.erp.common.inventory.entity.FeedPlanNoticeLine;
import com.mxpio.erp.common.inventory.service.FeedPlanNoticeService;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.service.ItemService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.inventory.policy.impl.DefaultToNoticePolicy;
import com.mxpio.erp.inventory.policy.impl.FeedPlanNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Tag(name = "FeedPlanNoticeController", description = "JIT送货计划单数据接口")
@RestController
@RequestMapping("/erp/inv/fp/")
public class FeedPlanNoticeController {

    @Autowired
    private FeedPlanNoticeService service;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderService bizOrderService;
    @GetMapping("list")
    @Operation(summary = "送货计划单列表", description = "获取送货计划单列表（无分页）", method = "GET")
    public Result<List<FeedPlanNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<FeedPlanNotice> notice = service.list(FeedPlanNotice.class, criteria);
        return Result.OK(notice);
    }

    @GetMapping("page")
    @Operation(summary = "送货计划单列表", description = "获取送货计划单列表（分页）", method = "GET")
    public Result<Page<FeedPlanNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<FeedPlanNotice> notice = service.listPage(FeedPlanNotice.class, page, criteria);
        return Result.OK(notice);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取送货计划单", description = "根据noticeNo获取送货计划单", method = "GET")
    public Result<FeedPlanNotice> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        FeedPlanNotice notice = service.getById(FeedPlanNotice.class, noticeNo);
        return Result.OK(notice);
    }

    @RequestMapping("save")
    @Operation(summary = "保存送货计划单", description = "保存送货计划单")
    public Result<FeedPlanNotice> save(@RequestBody FeedPlanNotice notice) {
        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof FeedPlanNoticeLine){
                    FeedPlanNotice receivingNotice = context.getParent();
                    ((FeedPlanNoticeLine) o).setNoticeNo(receivingNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除送货计划单", description = "删除送货计划单", method = "DELETE")
    public Result<FeedPlanNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(FeedPlanNotice.class, key);
        }
        return Result.OK();
    }

    @RequestMapping("execute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    @Transactional
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        FeedPlanNotice notice = service.getById(FeedPlanNotice.class, noticeNo);
        if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
        }
        bizOrderService.handleInQualityControl(notice.getPnCode(),orderExcuteVo.getLines());//判断物料是否入库检
        NoticeContext context = noticeService.execute(notice, new FeedPlanNoticePolicy(orderExcuteVo.getLines()));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @RequestMapping("execute_bat")
    @Operation(summary = "通知单批量执行", description = "通知单批量执行")
    @Transactional
    public Result<Object> excuteBat(@RequestBody List<OrderExcuteVo> orderExcuteVos) {
        if (orderExcuteVos.isEmpty()){
            return Result.error("入参为空");
        }
        for (OrderExcuteVo vo:orderExcuteVos){
            FeedPlanNotice notice = service.getById(FeedPlanNotice.class, vo.getNoticeNo());
            if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
                return Result.error("单据【"+notice.getNoticeNo()+"】状态已发生变化，已确认状态单据不允许重复确认！");
            }
            bizOrderService.handleInQualityControl(notice.getPnCode(),vo.getLines());//判断物料是否入库检
            NoticeContext context = noticeService.execute(notice, new FeedPlanNoticePolicy(vo.getLines()));
            if(CollectionUtils.isNotEmpty(context.getErrors())) {
                return Result.error(context.getErrors().get(0));
            }
        }
        return Result.OK();
    }

    @PutMapping("reject/{noticeNos}")
    @Operation(summary = "拒绝通知单，支持批量操作，通知单号用英文逗号分隔", description = "拒绝通知单，支持批量操作，通知单号用英文逗号分隔", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        if (StringUtils.isBlank(noticeNos)){
            return Result.error("入参为空");
        }
        String[] noticeNo = noticeNos.split(",");
        for (String key : noticeNo){
            Result<? extends Notice> colesResult = service.close(key);
            if (!colesResult.isSuccess()){
                return colesResult;
            }
        }
        return Result.OK();
    }

    @PutMapping("commit/{noticeNos}")
    @Operation(summary = "提交通知单，支持批量操作，通知单号用英文逗号分隔", description = "提交通知单，支持批量操作，通知单号用英文逗号分隔", method = "PUT")
    @Transactional
    public Result<? extends Notice> commit(@Parameter(description="通知单号") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        if (StringUtils.isBlank(noticeNos)){
            return Result.error("入参为空");
        }
        String[] noticeNoArray = noticeNos.split(",");
        for (String noticeNo : noticeNoArray){
            FeedPlanNotice notice = service.getById(FeedPlanNotice.class,noticeNo);
            if (!StringUtils.equals(notice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode())){
                return Result.error("【"+noticeNo+"】仅草稿状态的通知单允许提交操作");
            }
            if (StringUtils.isBlank(notice.getPnCode())){
                return Result.error("【"+noticeNo+"】请维护供应商信息！");
            }
            noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.CREATE);//更新为开立状态，相当于待审核
        }
        return Result.OK();
    }

    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应送货计划单及明细(打印用)", description = "根据noticeNos获取送货计划单及明细(打印，带供应商、生产订单)", method = "GET")
    public Result<List<FeedPlanNotice>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }
}
